import { ToastController } from 'ionic-angular/components/toast/toast-controller';
import { LoadingController } from 'ionic-angular/components/loading/loading-controller';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import { ActionSheetController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { BaseUI } from '../../common/baseui';
import { RestProvider } from '../../providers/rest/rest';
import { ModalController } from 'ionic-angular/components/modal/modal-controller';

import { File } from '@ionic-native/file'
import { Transfer, TransferObject } from '@ionic-native/transfer'
import { FilePath } from '@ionic-native/file-path'
import { Camera } from '@ionic-native/camera'
import { ViewController } from 'ionic-angular/navigation/view-controller';
import { normalizeURL } from 'ionic-angular/util/util';


declare var cordova: any  //导入第三方的库定义到TS项目中

/**
 * Generated class for the HeadfacePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-headface',
  templateUrl: 'headface.html',
})
export class HeadfacePage extends BaseUI{

  userId:string
  errorMessage: string
  lastImage: string = null

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public storage: Storage,
    public rest: RestProvider,
    public modalCtrl: ModalController,
    public loadingCtrl: LoadingController,
    public camera: Camera,
    public transfer: Transfer,
    public file: File,
    public filePath: FilePath,
    public platfrom: Platform,
    public toastCtrl: ToastController,
    public viewCtrl: ViewController,
    public actionSheetCtrl: ActionSheetController) {
      super()
  }

  ionViewDidEnter(){
   this.storage.get('userId').then(val => {
     console.log(val)
     if(val!=null) {
        this.userId = val
     }
   })
  }

  presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择图片',
      buttons: [
        {
          text: '从图片库中选择',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY)
          }
        },
        {
          text: '使用相机',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA)
          }
        },
        {
          text: '取消',
          role: 'cancel'
        }
      ]
    })
    actionSheet.present()
  }

  takePicture(sourceType) {
    // 定义相机的一些参数
    let options = {
      quality: 100,
      souceType: sourceType,
      saveToPhotoAlbum: false,
      correctOrientation: true  //是否纠正拍摄的照片的方向
    }
    // 获取图片的方法
    this.camera.getPicture(options).then(imagePath => {
      // 特别处理 android 平台文件路径问题
      if (this.platfrom.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
        this.filePath.resolveNativePath(imagePath) //获取android平台下的真实路径
        .then(filePath => {
          // 获取正确的路径
          let correctPath = filePath.substr(0, filePath.lastIndexOf('/')+1)
          // 获取正确的文件名
          let currentName = imagePath.substring(imagePath.lastIndexOf('/'+1), imagePath.lastIndexOf('?'))
          this.copyFileToLocalDir(correctPath, currentName, this.createFileName())
        })
      } else {
          // 获取正确的路径
          let correctPath = imagePath.substr(0, imagePath.lastIndexOf('/')+1)
          // 获取正确的文件名
          let currentName = imagePath.substring(imagePath.lastIndexOf('/')+1)
          this.copyFileToLocalDir(correctPath, currentName, this.createFileName())
          
      }
    },
    err => {
      super.showToast(this.toastCtrl, '选择图片出现错误，请在APP中操作或检查相关权限')
    })
  }

  // 将获取到的图片或相机拍摄到的图片进行一下另存为，用于后期图片上传使用
  copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success=> {
      this.lastImage = newFileName
    },
    error => {
      super.showToast(this.toastCtrl, '存储图片到本地图库出现错误')
    })
  }

  // 为文件生成一个新的文件名
  createFileName() {
    let d = new Date(),
    n = d.getTime(),
    newFileName = n + '.jpg' //拼接文件名
    return newFileName
  }

  // 处理图片的路径为可以上传的路径
  public pathForImage(img) {
    if(img === null) {
      return null
    } else {
      return normalizeURL(cordova.file.dataDirectory + img)
    }
  }

  uploadImage() {
    let url = 'https://imoocqa.gugujiankong.com/api/account/uploadheadface';
    let targetPath = this.pathForImage(this.lastImage)
    let filename = this.userId + '.jpg' //定义上传后的文件名
    
    // 上传的参数
    let options = {
      fileKey: 'file',
      fileName: filename,
      chunkedMode: false,
      mimeType: 'multipart/form-data',
      params: {'fileName': filename, 'userid': this.userId}
    }

    const fileTransfer: TransferObject = this.transfer.create()

    let loading = super.showLoading(this.loadingCtrl, '上传中...')

    // 开始正式的上传
    fileTransfer.upload(targetPath, url, options).then(data => {
      loading.dismissAll()
      super.showToast(this.toastCtrl,"图片上传成功")
      // 在用户看清弹窗提示后进行页面的关闭
      setTimeout(()=> {
        this.viewCtrl.dismiss()
      }, 3000)
    }, error => {
      loading.dismiss()
      super.showToast(this.toastCtrl,"图片上传发生错误，请重试")      
    })
  }
}
